package io.p2p.stream.turn.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.p2p.stream.turn.handler.TurnTcpServerHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class TurnTcpServer {

    @Getter
    @Setter
    private String name;

    @Getter
    @Setter
    private String host;

    @Getter
    @Setter
    private int port;

    private final EventLoopGroup bossGroup;

    private final EventLoopGroup workerGroup;

    private final ServerBootstrap serverBootstrap;

    public TurnTcpServer(String name, String host, int port) {
        this.name = name;
        this.host = host;
        this.port = port;

        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new TurnTcpServerHandler());
                    }
                });
    }

    public void start(CountDownLatch latch){
        try {
            Channel channel = serverBootstrap.bind(host, port).sync().channel();
            log.info("Stun TCP Server started on ip: {}, port: {}", host, port);

            // 在 channel 关闭时释放资源
            channel.closeFuture().addListener(future -> {
                log.info("Stun TCP Server is shutting down...");
                shutdown();
                latch.countDown(); // 通知主线程一个服务已关闭
            });
        } catch (InterruptedException e) {
            log.error("Failed to start TCP Server: {}", e.getMessage());
        }
    }

    public void shutdown() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
